package com.dhms.vostok1.model

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.dhms.basebusiness.BuildConfig
import com.tencent.mmkv.MMKV

open class SettingViewModel : ViewModel() {

    private lateinit var sharedPref: MMKV

    private val _settingMap = MutableLiveData(DEFAULT_SETTINGS)
    val settingMap: LiveData<HashMap<String, Any>> = _settingMap

    fun setSharedPreferences(sp: MMKV) {
        sharedPref = sp
    }

    fun writeSettings(setting: Map<String, Any>) {
        val settingItems = DEFAULT_SETTINGS.keys
        with(sharedPref.edit()) {
            setting.entries.forEach {
                if (it.key !in settingItems) {
                    throw Exception("Your setting item ${it.key} should be registered in the map $DEFAULT_SETTINGS.")
                }

                when (it.value) {
                    is Boolean -> putBoolean(it.key, it.value as Boolean)
                    is String -> putString(it.key, it.value as String)
                    is Int -> putInt(it.key, it.value as Int)
                    else -> {}
                }
            }
            apply()
        }
        _settingMap.value = settingMap.value!!.plus(setting) as HashMap<String, Any>
    }

    fun getSettings() {
        val tmpSettingMap = hashMapOf<String, Any>()
        DEFAULT_SETTINGS.entries.forEach {
            tmpSettingMap[it.key] = when (it.value) {
                is Boolean -> sharedPref.getBoolean(it.key, it.value as Boolean)
                is String -> sharedPref.getString(it.key, it.value as String)
                is Int -> sharedPref.getInt(it.key, it.value as Int)
                else -> it.value
            }!!
        }
        _settingMap.value = tmpSettingMap
    }

    val baseUrl: String?
        get() {
            return _settingMap.value?.entries?.firstOrNull { it.key == "BASE_URL" }?.value.toString()
        }

    @Suppress("UNCHECKED_CAST")
    fun <T> getSetting(key: String, defaultValue: T): T? {
        return when (defaultValue) {
            is Boolean -> sharedPref.getBoolean(key, defaultValue) as T
            is String -> sharedPref.getString(key, defaultValue) as T
            is Int -> sharedPref.getInt(key, defaultValue) as T
            else -> null
        }
    }

    companion object {
        val DEFAULT_SETTINGS = hashMapOf<String, Any>(
            "DEV_MODE" to false,
            "BASE_URL" to ""
        )
    }
}